﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using AMS.DD35.WebMVC3.Models;
using AMS.Core.Services;
using AMS.DD35.WcfConnector;
using AMS.Core.Data;
using AMS.Core.Cryptography;
using AMS.DD35.WebMVC3.State;

namespace AMS.DD35.WebMVC3.Controllers
{
    public class LoginController : Controller
    {
        ILoginService _login = new LoginProxy();
        IStateManager _state = new StateManager();

        //
        // GET: /Login/Login

        public ActionResult Login()
        {
            return View();
        }

        //
        // POST: /Login/Login

        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    IHasher hasher = new Hasher();
                    string pwHash = hasher.GetHash(model.Password);
                    LoginData lData = new LoginData(model.UserName, pwHash);
                    _state.SessionVariable = _login.AttemptLogin(lData);
                    _state.UserName = model.UserName;
                    return RedirectToAction("Index", "Character");

                }
                catch
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    return View(model);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Login/Logout

        public ActionResult Logout()
        {
            if (ModelState.IsValid)
            {
                try
                {
                    _login.Logout(_state.SessionVariable);
                    _state.SessionVariable = null;
                    _state.UserName = null;
                    _state.CharacterID = -1;
                    return RedirectToAction("Login", "Login");
                }
                catch { }
            }

            return RedirectToAction("Login", "Login");
        }
    }
}
